package com.shunda.pay.utils;

import com.alibaba.fastjson2.JSONObject;
import com.shunda.common.exception.ServiceException;
import com.shunda.pay.config.WxPayConfig;
import com.shunda.pay.dto.WxChatBasePayDto;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;

/**
 * 微信支付工具类
 */
public class WxPayUtil {

    private static final Logger log = LoggerFactory.getLogger(WxPayUtil.class);

    /**
     * 创建微信支付订单-jsapi方式
     *
     * @param wxPayConfig 微信配置信息
     * @param basePayData 基础请求信息，商品标题、商家订单id、订单价格
     * @return 微信支付二维码地址
     */
    public static PrepayWithRequestPaymentResponse wxJsApiPay(WxPayConfig wxPayConfig, WxChatBasePayDto basePayData, RSAAutoCertificateConfig rsaAutoCertificateConfig) {
        JsapiServiceExtension service =
                new JsapiServiceExtension.Builder()
                        .config(rsaAutoCertificateConfig)
                        .signType("RSA") // 不填默认为RSA
                        .build();

        PrepayWithRequestPaymentResponse response = new PrepayWithRequestPaymentResponse();
        try {
            PrepayRequest request = new PrepayRequest();
            request.setAppid(wxPayConfig.getAppId());
            request.setMchid(wxPayConfig.getMerchantId());
            request.setDescription(basePayData.getDescription());
            request.setOutTradeNo(basePayData.getOrderId());
            request.setNotifyUrl(wxPayConfig.getPayNotifyUrl());
            Amount amount = new Amount();
            amount.setTotal(basePayData.getPrice().multiply(new BigDecimal("100")).intValue());
            request.setAmount(amount);
            Payer payer = new Payer();
            payer.setOpenid(basePayData.getUserOpenId());
            request.setPayer(payer);
            log.info("请求预支付下单，请求参数：{}", JSONObject.toJSONString(request));
            // 调用预下单接口
            response = service.prepayWithRequestPayment(request);
            log.info("订单【{}】发起预支付成功，返回信息：{}", basePayData.getOrderId(), response);
        } catch (HttpException e) { // 发送HTTP请求失败
            log.error("微信下单发送HTTP请求失败，错误信息：{}", e.getHttpRequest());
        } catch (ServiceException e) { // 服务返回状态小于200或大于等于300，例如500
            log.error("微信下单服务状态错误，错误信息：{}", e.getMessage());
        } catch (MalformedMessageException e) { // 服务返回成功，返回体类型不合法，或者解析返回体失败
            log.error("服务返回成功，返回体类型不合法，或者解析返回体失败，错误信息：{}", e.getMessage());
        }
        return response;
    }

}
